import 'dart:ui';
import 'package:factoryside/api/api.dart';
import 'package:factoryside/bean/add_order_entity.dart';
import 'package:factoryside/bean/area_list_entity.dart';
import 'package:factoryside/bean/city_list_entity.dart';
import 'package:factoryside/bean/district_list_entity.dart';
import 'package:factoryside/bean/province_list_entity.dart';
import 'package:factoryside/home/line_chart_sample.dart';
import 'package:factoryside/home/page_next.dart';
import 'package:factoryside/service/order_service.dart';
import 'package:factoryside/utils/ColorsUtils.dart';
import 'package:factoryside/utils/mock_request.dart';
import 'package:factoryside/utils/request_util.dart';
import 'package:factoryside/utils/utils.dart';
import 'package:factoryside/widget/jh_login_textfield.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'bar_chart_sample.dart';

///发布工单

class CreateOrderPage extends StatefulWidget {
  int serviceType;//服务类型(1维修2安装3质保4.清洁5.用户送修)

  CreateOrderPage(this.serviceType);

  @override
  State<StatefulWidget> createState() {
    return _CreateOrderState();
  }
}

class _CreateOrderState extends State<CreateOrderPage>
    with AutomaticKeepAliveClientMixin {
  List values = List();
  ProvinceListData province;
  CityListDataData city;
  AreaListDataData area;
  DistrictListDataData district;
  String provinceName;
  String cityName;
  String areaName;
  String districtName;

//  var distinguishCon = TextEditingController(text:'李某某、 18000000000浙江省宁波市江北区同济路169号');
  var distinguishCon = TextEditingController();
  var nameCon = TextEditingController();
  var phoneCon = TextEditingController();
  var addrCon = TextEditingController();
  var addrDetailCon = TextEditingController();

  bool _hasSelected=false;
  bool _noSelected=false;
  bool _songSelected=false;

  bool _honaiSelected=false;
  bool _warrantySelected=false;

  AddOrderEntity _addOrderEntity=AddOrderEntity();

  String memo='';

  @override
  void initState() {
    super.initState();
//    RequestUtil.post(Api.getCityAll, {}).then((value) => null);
    setState(() {
      if(widget.serviceType==1){
        _hasSelected=false;
        _noSelected=true;
        _songSelected=false;
      }else if(widget.serviceType==2){
        _hasSelected=true;
        _noSelected=false;
        _songSelected=false;
      }else if(widget.serviceType==5){
        _hasSelected=false;
        _noSelected=false;
        _songSelected=true;
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context); //必须实现 不然 在push过后页面会刷新
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text('发布工单'),
      ),
      body: SafeArea(
        bottom: false,
        child: Container(
        color: ColorsUtil.hexToColor('#EFEFEF'),
        child: Column(children: [
          Expanded(
            child: ListView(
              children: [
                Container(
                  color: Colors.white,
                  margin: EdgeInsets.symmetric(vertical: 10),
                  padding: EdgeInsets.fromLTRB(10,10,10,0),
                  child: Column(
                    children: [
                      Container(
                          padding: EdgeInsets.all(10),
                          width: double.infinity,
                          decoration: BoxDecoration(
                              color: Color.fromARGB(180, 240, 240, 240),
//                    border: Border.all(
//                        width: 0.2, color: Colors.grey),
                              borderRadius: BorderRadius.all(Radius.circular(3))),
                          child: TextField(
                            controller: distinguishCon,
                            style: TextStyle(fontSize: 16, color: Colors.black),
                            maxLines: 4,
//                                    keyboardType: TextInputType.text,
                            decoration: InputDecoration(
                              hintText:
                              '粘贴整段文本加入文本框，自动识别：姓名、电话(例如：李某某、 18000000000浙江省宁波市江北区同济路169号)',
                              counterText: '',
                              disabledBorder: InputBorder.none,
                              enabledBorder: InputBorder.none,
                              focusedBorder: InputBorder.none,
                            ),
                          )),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          TextButton(onPressed: () {
                            setState(() {
                              distinguishCon.text='';
                            });
                          }, child: Text('清空')),
                          SizedBox(width: 10,),
                          ElevatedButton(onPressed: () {
                            var str=distinguishCon.text;
                            if(str.isEmpty){
                              showToast('内容不能为空');
                              return;
                            }
                            RequestUtil.post(Api.distinguish, {'conten':str}).then((value){
                              var data=value['Data']['Item2'];
                              nameCon.text=data['name'];
                              phoneCon.text=data['phone'];
                              addrDetailCon.text=data['addstr'];
                              if (data['province']!=null&&data['city']!=null&&data['area']!=null&&data['district']!=null) {
                                addrCon.text='${data['province']}${data['city']}${data['area']}${data['district']}';
                                _addOrderEntity.city='${data['province']}/${data['city']}/${data['area']}/${data['district']}';
                              }
                              memo='${data['bak']}';
                              setState(() {

                              });
                            });
                          }, child: Text('自动识别')),
                        ],
                      ),
                    ],
                  ),
                ),
                Container(
                  child: Column(
                    children: [
                      Container(
                        color: Colors.white,
                        padding: EdgeInsets.all(10),
                        child: Row(
                          children: [
                            Text('*客户姓名：'),
                            SizedBox(
                              width: 10,
                            ),
                            Expanded(
                              child: JhLoginTextField(
                                controller: nameCon,
                                hintText: '请输入姓名',
                                border: InputBorder.none,
                                isShowDeleteBtn: true,
                                isDense: true,
                              ),
                            )
                          ],
                        ),
                      ),
                      Divider(
                        height: 1,
                      ),
                      Container(
                        color: Colors.white,
                        padding: EdgeInsets.all(10),
                        child: Row(
                          children: [
                            Text('*联系电话：'),
                            SizedBox(
                              width: 10,
                            ),
                            Expanded(
                              child: JhLoginTextField(
                                controller: phoneCon,
                                hintText: '请输入电话',
                                border: InputBorder.none,
                                isShowDeleteBtn: true,
                                isDense: true,
                              ),
                            )
                          ],
                        ),
                      ),
                      Divider(
                        height: 1,
                      ),
                      GestureDetector(
                        child: Container(
                          color: Colors.white,
                          padding: EdgeInsets.all(10),
                          child: Row(
                            children: [
                              Text('*所在城市：'),
                              SizedBox(
                                width: 10,
                              ),
                              Expanded(
                                  child: JhLoginTextField(
                                    controller: addrCon,
                                    hintText: '所在地区',
                                    border: InputBorder.none,
                                    isShowDeleteBtn: false,
                                    isDense: true,
                                    enable: false,
                                  )),
                              Icon(
                                Icons.chevron_right,
                                color: Colors.grey,
                              )
                            ],
                          ),
                        ),
                        onTap: () {
                          OrderService.getProvince().then((value) {
                            setState(() {
                              values = value.data;
                              _showModalBottomSheet();
                            });
                          });
                        },
                      ),
                      Divider(
                        height: 1,
                      ),
                      Container(
                        color: Colors.white,
                        padding: EdgeInsets.all(10),
                        child: Row(
                          children: [
                            Text('*详细地址：'),
                            SizedBox(
                              width: 10,
                            ),
                            Expanded(
                              child: JhLoginTextField(
                                controller: addrDetailCon,
                                hintText: '街道门牌信息',
                                border: InputBorder.none,
                                isShowDeleteBtn: true,
                                isDense: true,
                              ),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top:10),
                  child: Column(
                    children: [
                      Container(
                        color: Colors.white,
                        padding: EdgeInsets.all(10),
                        child: Row(
                          children: [
                            Text('*服务类型：'),
                            Expanded(
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  // 复选框
                                  GestureDetector(
                                    behavior: HitTestBehavior.opaque,
                                    child: Row(
                                      children: [
                                        Container(
                                          padding: EdgeInsets.symmetric(vertical: 10,horizontal: 5),
                                          child: Image.asset(
                                            _hasSelected
                                                ? 'assets/checked.png'
                                                : 'assets/unchecked.png',
                                            width: 15,
                                            height: 15,
                                          ),
                                        ),
                                        Text('安装',
                                            textAlign: TextAlign.end,
                                            style: TextStyle(

                                                color: Colors.black)),
                                      ],
                                    ),
                                    onTap: () {
                                      setState(() {
                                        _hasSelected = true;
                                        _noSelected = false;
                                        _songSelected = false;
                                        widget.serviceType=2;
                                      });
                                    },
                                  ),
                                  GestureDetector(
                                    behavior: HitTestBehavior.opaque,
                                    child: Row(
                                      children: [
                                        Container(
                                          padding: EdgeInsets.symmetric(vertical: 10,horizontal: 5),
                                          child: Image.asset(
                                            _noSelected
                                                ? 'assets/checked.png'
                                                : 'assets/unchecked.png',
                                            width: 15,
                                            height: 15,
                                          ),
                                        ),
                                        Text('维修',
                                            textAlign: TextAlign.end,
                                            style: TextStyle(
                                                color: Colors.black)),
                                      ],
                                    ),
                                    onTap: () {
                                      setState(() {
                                        _hasSelected = false;
                                        _noSelected = true;
                                        _songSelected = false;
                                        widget.serviceType=1;
                                      });
                                    },
                                  ),
                                  Expanded(
                                    child: GestureDetector(
                                      behavior: HitTestBehavior.opaque,
                                      child: Row(
                                        children: [
                                          Container(
                                            padding: EdgeInsets.symmetric(vertical: 10,horizontal: 5),
                                            child: Image.asset(
                                              _songSelected
                                                  ? 'assets/checked.png'
                                                  : 'assets/unchecked.png',
                                              width: 15,
                                              height: 15,
                                            ),
                                          ),
                                          Expanded(
                                            child: Text('用户送修',
                                                style: TextStyle(
                                                    color: Colors.black)),
                                          ),
                                        ],
                                      ),
                                      onTap: () {
                                        setState(() {
                                          _hasSelected = false;
                                          _noSelected = false;
                                          _songSelected = true;
                                          widget.serviceType=5;
                                        });
                                      },
                                    ),
                                  ),
                                ],
                              ),
                            )
                          ],
                        ),
                      ),
                      Divider(
                        height: 1,
                      ),
                      Container(
                        color: Colors.white,
                        padding: EdgeInsets.all(10),
                        child: Row(
                          children: [
                            Text('*售后类型：'),
                            Expanded(
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  // 复选框
                                  GestureDetector(
                                    behavior: HitTestBehavior.opaque,
                                    child: Row(
                                      children: [
                                        Container(
                                          padding: EdgeInsets.symmetric(vertical: 10,horizontal: 5),
                                          child: Image.asset(
                                            _honaiSelected
                                                ? 'assets/checked.png'
                                                : 'assets/unchecked.png',
                                            width: 15,
                                            height: 15,
                                          ),
                                        ),
                                        Text('保内',
                                            textAlign: TextAlign.end,
                                            style: TextStyle(

                                                color: Colors.black)),
                                      ],
                                    ),
                                    onTap: () {
                                      setState(() {
                                        _honaiSelected = true;
                                        _warrantySelected = false;
                                      });
                                    },
                                  ),
                                  GestureDetector(
                                    behavior: HitTestBehavior.opaque,
                                    child: Row(
                                      children: [
                                        Container(
                                          padding: EdgeInsets.symmetric(vertical: 10,horizontal: 5),
                                          child: Image.asset(
                                            _warrantySelected
                                                ? 'assets/checked.png'
                                                : 'assets/unchecked.png',
                                            width: 15,
                                            height: 15,
                                          ),
                                        ),
                                        Text('保外',
                                            textAlign: TextAlign.end,
                                            style: TextStyle(

                                                color: Colors.black)),
                                      ],
                                    ),
                                    onTap: () {
                                      setState(() {
                                        _honaiSelected = false;
                                        _warrantySelected = true;
                                      });
                                    },
                                  ),
                                ],
                              ),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          Container(
              color: Colors.white,
              padding: EdgeInsets.fromLTRB(0,5,20,5),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  ElevatedButton(onPressed: () {
                    if(nameCon.text.isEmpty){
                      showToast('请输入姓名');
                      return;
                    }
                    if(phoneCon.text.isEmpty){
                      showToast('请输入电话');
                      return;
                    }
                    if(addrCon.text.isEmpty){
                      showToast('请选择所在地区');
                      return;
                    }
                    if(addrDetailCon.text.isEmpty){
                      showToast('请输入街道门牌信息');
                      return;
                    }
                    if(!_honaiSelected&&!_warrantySelected){
                      showToast('请选择售后类型');
                      return;
                    }
                    _addOrderEntity.servicetype=widget.serviceType;
                    _addOrderEntity.guaranteetype=_honaiSelected?1:2;
                    _addOrderEntity.name=nameCon.text;
                    _addOrderEntity.phone=phoneCon.text;
                    _addOrderEntity.addstr=addrDetailCon.text;
                    push(context, NextPage(_addOrderEntity,'${addrCon.text}${addrDetailCon.text}',memo));
                  }, child: Text('下一步')),
                ],
              )),
        ]),
      ),),
    );
  }

  /// 选择地址
  void _showModalBottomSheet() {
    var height = MediaQuery.of(context).size.height;
    showModalBottomSheet<int>(
      context: context,
      builder: (context) {
        return StatefulBuilder(builder: (context, state) {
          return Container(
            margin: EdgeInsets.all(10),
            height: height / 3 * 2,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Padding(
                    padding: EdgeInsets.all(10),
                    child: Text(
                      '请选择所在地区',
                      textAlign: TextAlign.center,
                    )),
                Divider(
                  height: 1,
                ),
                GestureDetector(
                    onTap: () {
                      state(() {
                        OrderService.getProvince().then((value) {
                          state(() {
                            values = value.data;
                          });
                        });
                      });
                    },
                    child: Padding(
                        padding: EdgeInsets.all(10),
                        child: Text(
                          province != null ? province.name : '请选择省',
                          style: TextStyle(color: Colors.grey),
                        ))),
                Visibility(
                    visible: province != null,
                    child: GestureDetector(
                      onTap: () {
                        state(() {
                          OrderService.getCity(province.code).then((value) {
                            state(() {
                              values = value.data.data;
                            });
                          });
                        });
                      },
                      child: Padding(
                          padding: EdgeInsets.all(10),
                          child: Text(
                            city != null ? city.name : '请选择市',
                            style: TextStyle(color: Colors.grey),
                          )),
                    )),
                Visibility(
                    visible: city != null,
                    child: GestureDetector(
                      onTap: () {
                        state(() {
                          OrderService.getArea(city.code).then((value) {
                            state(() {
                              values = value.data.data;
                            });
                          });
                        });
                      },
                      child: Padding(
                          padding: EdgeInsets.all(10),
                          child: Text(
                            area != null ? area.name : '请选择区',
                            style: TextStyle(color: Colors.grey),
                          )),
                    )),
                Visibility(
                    visible: area != null,
                    child: GestureDetector(
                      onTap: () {
                        state(() {
                          OrderService.getDistrict(area.code).then((value) {
                            state(() {
                              values = value.data.data;
                            });
                          });
                        });
                      },
                      child: Padding(
                          padding: EdgeInsets.all(10),
                          child: Text(
                            district != null ? district.name : '请选择街道',
                            style: TextStyle(color: Colors.grey),
                          )),
                    )),
                Divider(),
                Expanded(
                  child: ListView(
                    shrinkWrap: true,
                    children: values
                        .map((e) => GestureDetector(
                      onTap: () {
                        state(() {
                          if (e is ProvinceListData) {
                            province = e;
                            provinceName = e.name;
                            OrderService.getCity(province.code)
                                .then((value) {
                              state(() {
                                values = value.data.data;
                              });
                            });
                          } else if (e is CityListDataData) {
                            city = e;
                            cityName = e.name;
                            OrderService.getArea(city.code)
                                .then((value) {
                              state(() {
                                values = value.data.data;
                              });
                            });
                          } else if (e is AreaListDataData) {
                            area = e;
                            areaName = e.name;
                            OrderService.getDistrict(area.code)
                                .then((value) {
                              state(() {
                                var tempList=value.data.data;
                                tempList.add(DistrictListDataData.initName('不知道'));
                                values = tempList;
                              });
                            });
                          } else if (e is DistrictListDataData) {
                            district = e;
                            districtName = e.name;
                            Navigator.of(context).pop();
                            setState(() {
                              if (districtName!='不知道') {
                                addrCon.text =
                                                              '$provinceName$cityName$areaName$districtName';
                                _addOrderEntity.city='$provinceName/$cityName/$areaName/$districtName';
                              }else{
                                addrCon.text =
                                '$provinceName$cityName$areaName';
                                _addOrderEntity.city='$provinceName/$cityName/$areaName/$districtName';
                              }
                            });
                          }
                        });
                      },
                      child: Padding(
                        padding: EdgeInsets.all(10),
                        child: Text(e.name),
                      ),
                    ))
                        .toList(),
                  ),
                )
              ],
            ),
          );
        });
      },
      elevation: 10,
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(10), topRight: Radius.circular(10))),
    );
  }

}
